<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时聊天</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        #chatBox {
            width: 100%;
            height: 300px;
            border: 1px solid #ccc;
            overflow-y: auto;
            padding: 10px;
        }
        #messageInput {
            width: 80%;
        }
        button {
            width: 15%;
        }
    </style>
</head>
<body>

<h2>实时聊天</h2>
<div id="chatBox"></div>
<input type="text" id="messageInput" placeholder="请输入消息...">
<button onclick="sendMessage()">发送</button>

<script>
    var ws = new WebSocket("ws://localhost:8080/chat");

    ws.onopen = function() {
        console.log("已连接到聊天服务器");
    };

    ws.onmessage = function(event) {
        var chatBox = document.getElementById("chatBox");
        chatBox.innerHTML += "<p>" + event.data + "</p>";
        chatBox.scrollTop = chatBox.scrollHeight;  // 自动滚动到最新消息
    };

    ws.onclose = function() {
        console.log("与服务器的连接已关闭");
    };

    ws.onerror = function(error) {
        console.log("WebSocket 错误: " + error);
    };

    function sendMessage() {
        var messageInput = document.getElementById("messageInput");
        var message = messageInput.value;
        if (message.trim() !== "") {
            ws.send(message);
            messageInput.value = "";
        }
    }
</script>

</body>
</html>
